/*
 * Copyright (c) 2009.
 * nick@tmro.net
 */
package net.tmro.loko.web.managedbeans;

import net.tmro.loko.domain.store.Store;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

public class StoreConverter implements Converter {

    public StoreConverter() {
    }

    public Object getAsObject(FacesContext facesContext, UIComponent uIComponent, String string) {
        if (string == null || string.trim().length() == 0) {
            return null;
        }

        StoreManagedBean managedBean = (StoreManagedBean) facesContext.getApplication().getVariableResolver().resolveVariable(
                facesContext, "store");

        final Long id = new Long(string);

        return managedBean.findEntity(id);
    }

    public String getAsString(FacesContext facesContext, UIComponent uIComponent, Object object) {
        if (object == null) return null;

        if (object instanceof Store) {
            Store entity = (Store) object;

            final String pk = String.valueOf(entity.getId());

            return pk;
        } else {
            throw new IllegalArgumentException("Incorrect object type: " + object.getClass().getName() + "; must be: Store");
        }
    }
}
